﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WHC.Hotel.Entity;
using WHC.Hotel.BLL;


using WHC.OrderWater.Commons;
using WHC.Security.Entity;


namespace WHC.Hotel.UI
{
    public partial class FrmPurchase : BaseForm
    {
        public FrmPurchase()
        {
            InitializeComponent();
        }

        private void InitDictItem()
        {
            this.txtManufacture.Items.Clear();
            this.txtSearchManufacture.Items.Clear();
            List<ManufactureInfo> list = BLLFactory<Manufacture>.Instance.GetAll();
            foreach (ManufactureInfo info in list)
            {
                this.txtManufacture.Items.Add(info.Name);
                this.txtSearchManufacture.Items.Add(info.Name);
            }

            this.txtWareHouse.Items.Clear();
            this.txtWareHouse.Items.AddRange(DictItemUtil.GetWareHouse(false));
            this.txtSearchWareHouse.Items.Clear();
            this.txtSearchWareHouse.Items.AddRange(DictItemUtil.GetWareHouse(true));

            this.txtCreator.Items.Clear();
            this.txtSearchOperator.Items.Clear();
            List<UserInfo> userList = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.User>.Instance.GetAll();
            foreach (UserInfo info in userList)
            {
                this.txtCreator.Items.Add(info.FullName);
                this.txtSearchOperator.Items.Add(info.FullName);
            }
            this.txtCreator.SelectedIndex = this.txtCreator.FindString(Portal.gc.LoginInfo.FullName);

            this.dtStart.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            this.dtEnd.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));

            this.txtHandNo.Text = BLLFactory<PurchaseHeader>.Instance.GetHandNumber(true);//进货单号
        }
        
        private void FrmPurchase_Load(object sender, EventArgs e)
        {
            InitDictItem();

            this.winGridView1.ProgressBar = this.toolStripProgressBar1.ProgressBar;
            this.winGridView1.AppendedMenu = this.contextMenuStrip2;
            this.winGridView1.dataGridView1.RowEnter += new DataGridViewCellEventHandler(dataGridView1_RowEnter);

            this.winGridView2.ProgressBar = this.toolStripProgressBar1.ProgressBar;
            this.winGridView2.AppendedMenu = this.contextMenuStrip3;
            
            #region 添加别名解析
            this.winGridView2.AddColumnAlias("HandNo", "货单号");
            this.winGridView2.AddColumnAlias("ItemNo", "项目编号");
            this.winGridView2.AddColumnAlias("ItemName", "项目名称");
            this.winGridView2.AddColumnAlias("Unit", "单位");
            this.winGridView2.AddColumnAlias("Price", "单价");
            this.winGridView2.AddColumnAlias("Quantity", "数量");
            this.winGridView2.AddColumnAlias("Amount", "应收金额");
            #endregion
        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            BindDetail();
        }

        private void BindDetail()
        {
            DataGridViewRow row;
            for (int i = 0; i < winGridView1.dataGridView1.SelectedRows.Count; i++)
            {
                row = winGridView1.dataGridView1.SelectedRows[i];
                string headID = row.Cells["ID"].Value.ToString();
                if (!string.IsNullOrEmpty(headID))
                {
                    this.winGridView2.PrintTitle = Portal.gc.gAppUnit + " -- " + string.Format("采购单[{0}]的货品列表", headID);
                    this.winGridView2.DisplayColumns = "HandNo,ItemNo,ItemName,Unit,Price,Quantity,Amount";

                    DataTable dt = BLLFactory<PurchaseDetail>.Instance.GetPurchaseDetailReportByID(Convert.ToInt32(headID));
                    decimal amount = 0M;
                    foreach (DataRow dr in dt.Rows)
                    {
                        amount += Convert.ToDecimal(dr["Amount"].ToString());
                    }
                    dt.Rows.Add(dt.NewRow());
                    dt.Rows.Add(dt.NewRow());

                    DataRow myRow = dt.NewRow();
                    myRow["Amount"] = amount.ToString();
                    dt.Rows.Add(myRow);

                    this.winGridView2.DataSource = dt.DefaultView;
                }

                break;
            }
        }

        private void BinData()
        {
            this.winGridView1.DisplayColumns = "ID,HandNo,OperationType,Manufacture,WareHouse,Yinfu,Paid,YinShou,Received,Note,CreateDate,Creator";

            #region 添加别名解析
            this.winGridView1.AddColumnAlias("ID", "编号");
            this.winGridView1.AddColumnAlias("HandNo", "货单编号");
            this.winGridView1.AddColumnAlias("CreateDate", "日期");
            this.winGridView1.AddColumnAlias("Manufacture", "供货商");
            this.winGridView1.AddColumnAlias("Creator", "经手员工");
            this.winGridView1.AddColumnAlias("Yinfu", "应付账款");
            this.winGridView1.AddColumnAlias("Paid", "已付账款");
            this.winGridView1.AddColumnAlias("YinShou", "应收账款");
            this.winGridView1.AddColumnAlias("Received", "已收账款");
            this.winGridView1.AddColumnAlias("OperationType", "进货/出货");
            this.winGridView1.AddColumnAlias("WareHouse", "仓库名称");
            this.winGridView1.AddColumnAlias("Note", "备注信息");
            #endregion

            SearchCondition condition = new SearchCondition();
            condition.AddCondition("CreateDate", this.dtStart.Value.ToString(), SqlOperator.MoreThanOrEqual)
                .AddCondition("CreateDate", this.dtEnd.Value.ToString(), SqlOperator.LessThanOrEqual)
                .AddCondition("Manufacture", this.txtSearchManufacture.Text, SqlOperator.Like)
                .AddCondition("Creator", this.txtSearchOperator.Text, SqlOperator.Like)
                .AddCondition("WareHouse", this.txtSearchWareHouse.Text.Replace("所有仓库",""), SqlOperator.Like)
                .AddCondition("OperationType", "进货", SqlOperator.Equal);
            string filter = condition.BuildConditionSql(DatabaseType.SqlServer);

            DataTable dt = BLLFactory<PurchaseHeader>.Instance.GetPurchaseReport(filter);
            decimal yinfu = 0M;
            decimal paid = 0M;
            decimal yinShou = 0M;
            decimal received = 0M;
            foreach (DataRow row in dt.Rows)
            {
                yinfu += Convert.ToDecimal(row["Yinfu"].ToString());
                paid += Convert.ToDecimal(row["Paid"].ToString());
                yinShou += Convert.ToDecimal(row["YinShou"].ToString());
                received += Convert.ToDecimal(row["Received"].ToString());
            }
            dt.Rows.Add(dt.NewRow());
            dt.Rows.Add(dt.NewRow());
            DataRow dr = dt.NewRow();
            dr["Yinfu"] = yinfu.ToString();
            dr["Paid"] = paid.ToString();
            dr["YinShou"] = yinShou.ToString();
            dr["Received"] = received.ToString();
            dt.Rows.Add(dr);

            this.winGridView1.DataSource = dt.DefaultView;
            this.winGridView1.PrintTitle = Portal.gc.gAppUnit + " -- " + "采购单查询报表";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.txtWareHouse.Text == "")
            {
                MessageUtil.ShowTips("请选择仓库");
                return;
            }

            FrmAddPurchaseGoods dlg = new FrmAddPurchaseGoods();
            dlg.WareHourse = this.txtWareHouse.Text;
            dlg.HandNumber = this.txtHandNo.Text;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                int i = 1;
                foreach (PurchaseDetailInfo info in dlg.detailDict.Values)
                {
                    ListViewItem item = new ListViewItem(info.ItemNo);
                    item.SubItems.Add(info.ItemName);
                    item.SubItems.Add(info.Unit);
                    item.SubItems.Add(info.Price.ToString("C2"));
                    item.SubItems.Add(info.Quantity.ToString());
                    item.SubItems.Add(info.Amount.ToString("C2"));
                    item.SubItems.Add(info.DuralDays.ToString());
                    item.SubItems.Add(info.ExpireDate.ToString("yyyy-MM-dd"));
                    item.Tag = info;

                    this.lvwDetail.Items.Add(item);
                    i++;
                }
                CaculateMoney();
            }
        }

        private void CaculateMoney()
        {
            decimal allMoney = 0M;
            for (int i = 0; i < this.lvwDetail.Items.Count; i++)
            {
                PurchaseDetailInfo info = this.lvwDetail.Items[i].Tag as PurchaseDetailInfo;
                if (info != null)
                {
                    allMoney += info.Amount;
                }
            }
            this.txtYinfu.Text = allMoney.ToString("f2");
            this.txtPaid.Text = allMoney.ToString("f2");
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.lvwDetail.SelectedItems.Count == 0) return;
            for (int i = this.lvwDetail.SelectedItems.Count - 1; i >= 0; i--)
            {
                this.lvwDetail.Items.RemoveAt(i);
            }
            CaculateMoney();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            #region 验证输入
            if (this.txtHandNo.Text.Trim() == "")
            {
                MessageUtil.ShowTips("货单编号不能为空");
                this.txtHandNo.Focus();
                return;
            }
            else if (this.txtManufacture.Text.Trim() == "")
            {
                MessageUtil.ShowTips("请选择供应商");
                this.txtManufacture.Focus();
                return;
            }
            else if (this.txtWareHouse.Text.Trim() == "")
            {
                MessageUtil.ShowTips("请选择仓库");
                this.txtWareHouse.Focus();
                return;
            }
            else if (this.lvwDetail.Items.Count == 0)
            {
                MessageUtil.ShowTips("请添加商品");
                return;
            }
            else if (this.txtCreator.Text.Length == 0)
            {
                MessageUtil.ShowTips("请选择经手人");
                return;
            }
            #endregion

            try
            {
                PurchaseHeaderInfo headInfo = new PurchaseHeaderInfo();
                headInfo.CreateDate = txtCreateDate.Value;
                headInfo.Creator = this.txtCreator.Text;
                headInfo.HandNo = this.txtHandNo.Text;
                headInfo.Manufacture = this.txtManufacture.Text;
                headInfo.Note = this.txtNote.Text;
                headInfo.OperationType = "进货";
                headInfo.Yinfu = Convert.ToDecimal(this.txtYinfu.Text);
                headInfo.Paid = Convert.ToDecimal(this.txtPaid.Text);
                headInfo.WareHouse = this.txtWareHouse.Text;
                //headInfo.YinShou = Convert.ToDecimal(this.txtPaid.Text);
                //headInfo.Received = Convert.ToDecimal(this.txtPaid.Text);

                int headId = BLLFactory<PurchaseHeader>.Instance.Insert2(headInfo);
                if (headId > 0)
                {
                    for (int i = 0; i < this.lvwDetail.Items.Count; i++)
                    {
                        PurchaseDetailInfo detailInfo = this.lvwDetail.Items[i].Tag as PurchaseDetailInfo;
                        if (detailInfo != null)
                        {
                            detailInfo.PurchaseHead_ID = headId;
                            BLLFactory<PurchaseDetail>.Instance.Insert(detailInfo);
                            AddStockQuantity(detailInfo);//增加库存
                        }
                    }

                    MessageUtil.ShowTips("保存成功");
                    ClearContent();
                }
                else
                {
                    MessageUtil.ShowError("保存失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                MessageUtil.ShowError(ex.Message);
            }
        }

        private void AddStockQuantity(PurchaseDetailInfo detailInfo)
        {
            string WareHourse = this.txtWareHouse.Text;
            if (WareHourse == "客房仓库")
            {
                BLLFactory<Goods>.Instance.AddStockQuantiy(detailInfo.ItemNo, detailInfo.ItemName, Convert.ToInt32(detailInfo.Quantity));
            }
            else if (WareHourse == "KTV仓库")
            {
                BLLFactory<KTVGoods>.Instance.AddStockQuantiy(detailInfo.ItemNo, detailInfo.ItemName, Convert.ToInt32(detailInfo.Quantity));
            }
            else if (WareHourse == "茶室仓库")
            {
                BLLFactory<TeaGoods>.Instance.AddStockQuantiy(detailInfo.ItemNo, detailInfo.ItemName, Convert.ToInt32(detailInfo.Quantity));
            }
        }

        private void ClearContent()
        {
            this.txtHandNo.Text = BLLFactory<PurchaseHeader>.Instance.GetHandNumber(true);//进货单号
            this.lvwDetail.Items.Clear();
            CaculateMoney();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            BinData();
        }

        private void menu_InRefresh_Click(object sender, EventArgs e)
        {
            CaculateMoney();
        }

        private void menu_Delete_Click(object sender, EventArgs e)
        {
            btnDelete_Click(null, null);
        }

        private void btnModifyExpired_Click(object sender, EventArgs e)
        {
            if (this.lvwDetail.SelectedItems.Count == 0) return;

            PurchaseDetailInfo info = this.lvwDetail.SelectedItems[0].Tag as PurchaseDetailInfo;
            if (info != null)
            {
                FrmEditExpiredDate dlg = new FrmEditExpiredDate();
                dlg.txtDuralDays.Text = info.DuralDays.ToString();
                dlg.txtExpired.Value = info.ExpireDate;
                dlg.txtItemNo.Text = info.ItemNo;
                dlg.txtName.Text = info.ItemName;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    info.ExpireDate = dlg.txtExpired.Value;

                    this.lvwDetail.SelectedItems[0].SubItems[7].Text = info.ExpireDate.ToString("yyyy-MM-dd");
                }
            }
            
        }

        private void txtSearchWareHouse_SelectedIndexChanged(object sender, EventArgs e)
        {
            BinData();
        }

        private void menu_DetailRefresh_Click(object sender, EventArgs e)
        {
            BinData();
        }

        private void menu_Detail_Money_Click(object sender, EventArgs e)
        {
            if (this.winGridView1.dataGridView1.SelectedRows.Count == 0)
                return;
            DataGridViewRow row;
            for (int i = 0; i < winGridView1.dataGridView1.SelectedRows.Count; i++)
            {
                row = winGridView1.dataGridView1.SelectedRows[i];
                string ID = row.Cells["ID"].Value.ToString();
                if (!string.IsNullOrEmpty(ID))
                {
                    PurchaseHeaderInfo detailInfo = BLLFactory<PurchaseHeader>.Instance.FindByID(ID);
                    if (detailInfo != null)
                    {
                        FrmEditPayReceived dlg = new FrmEditPayReceived();
                        dlg.lblBillNo.Text = detailInfo.HandNo;
                        dlg.lblBillType.Text = detailInfo.OperationType;
                        dlg.txtPaid.Text = detailInfo.Paid.ToString("f2");
                        dlg.txtReceived.Text = detailInfo.Received.ToString("f2");
                        dlg.txtYinfu.Text = detailInfo.Yinfu.ToString("f2");
                        dlg.txtYinShou.Text = detailInfo.YinShou.ToString("f2");

                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            detailInfo.Yinfu = Convert.ToDecimal(dlg.txtYinfu.Text);
                            detailInfo.YinShou = Convert.ToDecimal(dlg.txtYinShou.Text);
                            detailInfo.Paid = Convert.ToDecimal(dlg.txtPaid.Text);
                            detailInfo.Received = Convert.ToDecimal(dlg.txtReceived.Text);

                            BLLFactory<PurchaseHeader>.Instance.Update(detailInfo, ID);

                            BinData();
                        }
                    }
                }

                break;
            }
        }
    }
}
